import { Flex, useColorModeValue } from '@chakra-ui/react';
import { useAppDispatch } from 'app/store/storeHooks';
import IAIIconButton from 'common/components/IAIIconButton';
import TFSlider from 'common/components/TFSlider';
import { memo, useCallback } from 'react';
import { FaTrash } from 'react-icons/fa';
import { useTranslation } from 'react-i18next';
import {
  LoRA,
  loraRemoved,
  loraWeightChanged,
  loraWeightReset,
} from '../store/loraSlice';

type Props = {
  lora: LoRA;
};

const ParamLora = (props: Props) => {
  const { t } = useTranslation();
  const dispatch = useAppDispatch();
  const { lora } = props;

  const handleChange = useCallback(
    (v: number) => {
      dispatch(loraWeightChanged({ id: lora.id, weight: v }));
    },
    [dispatch, lora.id]
  );

  const handleReset = useCallback(() => {
    dispatch(loraWeightReset(lora.id));
  }, [dispatch, lora.id]);

  const handleRemoveLora = useCallback(() => {
    dispatch(loraRemoved(lora.id));
  }, [dispatch, lora.id]);

  return (
    <Flex
      w="full"
      gap="2"
      p="2"
      rounded="base"
      bg={useColorModeValue('base.900', 'base.800')}
      pos="relative"
    >
      <Flex
        flexShrink={0}
        w="60px"
        h="60px"
        bg={useColorModeValue('base.800', 'base.700')}
        rounded="base"
      ></Flex>
      <TFSlider
        label={lora.model_name}
        value={lora.weight}
        onChange={handleChange}
        min={-1}
        max={2}
        step={0.01}
        withInput
        handleReset={handleReset}
        withSliderMarks
        sliderMarks={[-1, 0, 1, 2]}
        sliderNumberInputProps={{ min: -50, max: 50, maxW: '64px' }}
        sliderFormLabelProps={{ mb: 1.5 }}
        sliderFormControlProps={{
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'space-between',
        }}
        sliderProps={{
          maxW: '110px',
        }}
      />
      <IAIIconButton
        pos="absolute"
        right="-1"
        top="-1"
        size="sm"
        onClick={handleRemoveLora}
        tooltip={t('parameters.removeLoRA')}
        aria-label={t('parameters.removeLoRA')}
        icon={<FaTrash />}
        bg="transparent"
        sx={{
          svg: {
            fill: 'base.700',
          },
          _hover: {
            bg: 'transparent',
            svg: {
              fill: 'error.600',
            },
          },
        }}
      />
    </Flex>
  );
};

export default memo(ParamLora);
